package com.shigu.core.config;

import com.shigu.admin.manager.common.JSONResult;
import com.shigu.main4.common.exceptions.Main4Exception;
import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 异常拦截
 * 
 * @author wxc
 * @date 2016年6月15日 上午11:21:14
 */
@Component
public class ExceptionResolver extends SimpleMappingExceptionResolver {

	private static final Logger logger = LoggerFactory.getLogger(ExceptionResolver.class);
	@Override
	protected ModelAndView doResolveException(HttpServletRequest request,
			HttpServletResponse response, Object arg2, Exception ex) {
        String message = ex.getMessage()==null?"请求失败，联系管理员":ex.getMessage();
        if(request.getServletPath().endsWith(".json")){//json类型的问题
			String jsonString = JSONResult.error(message).toString();
			response.setCharacterEncoding("UTF-8");
			if (request.getParameter("callback") != null) {
				response.setContentType("application/x-javascript");//jsonp异常响应处理
				jsonString = request.getParameter("callback") + "(" + jsonString + ");";
			} else {
				response.setContentType("application/json");//修复post异常信息未被解析为json
			}
			PrintWriter writer;
			try {
				writer = response.getWriter();
				writer.print(jsonString);
				writer.flush();
				writer.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}else if(ex instanceof Main4Exception){//页面已知的错误
			request.setAttribute("errMsg", message);
		}else if(ex instanceof UnauthorizedException){//权限错误
			return getModelAndView("common/403", ex, request);
		}else{//页面未知的错误
			request.setAttribute("errMsg","管理系统异常");
			logger.error(message, ex);
		}
		//记录异常日志...
		return getModelAndView("common/500", ex, request);
	}
}
